<?php
/*
+--------------------------------------------------------------------------
|   Anwsion [#RELEASE_VERSION#]
|   ========================================
|   by Tatfook Network Team
|   (c) 2011 - 2012 Anwsion Software
|   http://www.anwsion.com
|   ========================================
|   Support: zhengqiang@gmail.com
|   
+---------------------------------------------------------------------------
*/

define('IN_AJAX', TRUE);

class c_ajax_class extends AWS_CONTROLLER
{
	var $per_page = 10;

	public function get_access_rule()
	{
		$rule_action['rule_type'] = 'white'; //黑名单,黑名单中的检查  'white'白名单,白名单以外的检查
		$rule_action['actions'] = array(
			'topic_info',
			'log_bit',
			'get_all_best_question',
			'get_all',
			'get_focus_users'
		);
		
		return $rule_action;
	}

	function setup()
	{
		HTTP::no_cache_header();
	}

	public function get_focus_users_action()
	{
		$focus_users = $this->model('topic')->get_focus_users_by_topic($_GET['topic_id']);
		
		
		if (is_array($focus_users))
		{
			foreach ($focus_users as $key => $val)
			{
				$focus_users[$key]['avatar_file'] = get_avatar_url($val['uid'], 'mid', $val['avatar_file']);
			}
		}
		
		H::ajax_json_output($focus_users);
	}

	public function get_all_action()
	{
		$limit = intval($_GET['page']) * $this->per_page;
		$num = intval($_GET['num']);
		
		if ($num > 0)
		{
			$limit = $limit . ", " . $num;
		}
		else
		{
			$limit = $limit . ", {$this->per_page}";
		}

		//$limit=calc_page_limit($_GET['page'],$this->per_page);
		
		$questions_row_array = array(); // 问题ID内容集合,符合条件
		$questions_array = array(); // 我关注的话题的问题集合
		$cache_key = ZCACHE::format_key('topics_get_all_by_topic_v2_' . $_GET['topic_id'] . $limit);
		$action_list = ZCACHE::get($cache_key);
		//$action_lis=false;

		
		if ($action_list === false)
		{
			if ($list = $this->model('topic')->get_all_by_topic_v2($_GET['topic_id'], $limit))
			{			
				foreach ($list as $key => $val)
				{
					if ($val['question_id'] > 0)
					{
						$questions_row_array[$val['question_id']] = $val;
						$questions_array[] = $val['question_id'];
					}
				
				}
			}
			// 101 添加问题
			// 102 编辑问题标题
			// 103 编辑问题描述
			// 104 删除问题
			// 105 添加问题关注
			// 106 删除问题关注
			//
			// 201 回复问题
			// 202 编辑回复
			// 203 删除回复
			// 204 赞成回复
			// 205 反对回复
			//
			// 301 增加评论
			// 302 删除评论
			//
			// 401 创建话题
			// 402 编辑话题
			// 403 编辑话题描述
			// 404 编辑话题缩图
			// 405 删除话题
			//
			// 406 添加话题关注
			// 407 删除话题关注
			// 408 增加话题父类
			// 409 删除话题父类
			//
			// 501 添加比赛
			// 502 比赛报名
			// 503 提交作品
			// 504 编辑作品
			// 505 添加比赛关注
			// 506 删除比赛关注
			

			$action_question = '101,201';
			$action_competitions = '501,503';
			$questions_array[] = 0;
			
			if ($questions_array)
			{
				$where[] = "(associate_type='" . ACTION_LOG::CATEGORY_QUESTION . "' AND  associate_id in (" . implode($questions_array, ",") . ") AND  associate_action IN({$action_question}))";
			}
			
			// echo implode($where, ' OR ');die;
			// 限定动作
			if ($where)
			{
				$action_list = ACTION_LOG::get_actions_distint_by_where(implode($where, ' OR '), '');
			}
			
			
			
			foreach ($action_list as $key => $val)
			{
				$action_list[$key]['add_time'] = $val['add_time'];
				
				if (! isset($user_info_list[$val['uid']]))
				{
					$user_info_more_list[$val['uid']] = $this->model('account')->get_users_by_uid($val['uid'], true);
					$user_info_list[$val['uid']] = $user_info_more_list[$val['uid']]['user_name'];
				}
				
				$action_list[$key]['user_info'] = $user_info_more_list[$val['uid']];
				
				switch ($val['associate_type'])
				{
					case ACTION_LOG::CATEGORY_QUESTION :
						
						$index_focus_type = 1;
						$question_info = $this->model('question')->get_question_info_by_id($val['associate_id']);
						
						//是否关注
						if ($this->model('question')->has_focus_question($question_info['question_id'], $this->user_id))
						{
							$question_info['has_focus'] = true;
						}
						else
						{
							$question_info['has_focus'] = false;
						}
						
						if (! $user_info_list[$val['uid']])
						{
							$user_info_list[$val['uid']] = $this->model('account')->get_users($val['uid']);
						}
						
						$question_info['last_user_name'] = $user_info_list[$val['uid']];
						$question_info['last_user_avatar_file'] = $user_info_more_list[$val['uid']]['avatar_file'];
						$question_info['last_user_uid'] = $val['uid'];
						
						if (in_array($val['associate_action'], array(
							401, 
							402, 
							403, 
							404, 
							405, 
							406, 
							407, 
							408, 
							409
						)))
						{
							$topic_info = $this->model('topic')->get_topic($val['associate_attached']);
						
						}
						
						if (in_array($val['associate_action'], array(
							101
						)))
						{
							$question_info['attachs'] = $this->model('publish')->get_attach('question', $question_info['question_id'], 'min'); // 获取附件
						}
						
						$question_info['last_action_str'] = ACTION_LOG::format_action_str($val['associate_action'], $val['uid'], $user_info_list[$val['uid']], null, $topic_info, 1);
						
						if (in_array($val['associate_action'], array(
							201
						)))
						{
							$answer_list = $this->model('answer')->get_answer_info_by_id($val['associate_attached']);
							$answer_list['attachs'] = $this->model('publish')->get_attach('answer', $val['associate_attached'], 'min'); //获取附件
							
						
							$answer_list['uname'] = $user_info_more_list[$val['uid']]['user_name'];
							$answer_list['avatar_file'] = $user_info_more_list[$val['uid']]['avatar_file'];
							$answer_list['signature'] = $user_info_more_list[$val['uid']]['signature'];
							$answer_list['answer_content']=strip_ubb($answer_list['answer_content']);
						
						}
						else
						{
							$answer_list = null;
						}
						
						$user_arr = array();
						
						if (! empty($answer_list))
						{
							$question_info['answer_info'] = $answer_list;
						}
						
						if ($question_info['answer_info']['agree_count'] > 0)
						{
							$question_info['answer_info']['agree_users'] = $this->model("answer")->get_vote_user_by_answer_id($question_info['answer_info']['answer_id']);
						}
						
						$answer_vote = $this->model("answer")->get_answer_vote_status($question_info['answer_info']['answer_id'], $this->user_id);
						
						$question_info['answer_info']['agree_status'] = intval($answer_vote['vote_value']);
						
						// 还原到单个数组ROW里面
							foreach ($question_info as $qkey => $qval)
							{
								if ($qkey == 'add_time')
									continue;
								$action_list[$key][$qkey] = $qval;
							}
						
						break;
				
				}
			
			}
			
			
			
			ZCACHE::set($cache_key, $action_list, null, get_setting('cache_level_high'));
		}
		
		TPL::assign('list', $action_list);
		
		TPL::output('topic/ajax/get_all');
	
	}
	
	public function get_all_best_question_action()
	{
		$limit = intval($_GET['page']) * $this->per_page;
		$num = intval($_GET['num']);
		
		if ($num > 0)
		{
			$limit = $limit . ", " . $num;
		}
		else
		{
			$limit = $limit . ", {$this->per_page}";
		}
		
		$questions_row_array = array(); // 问题ID内容集合,符合条件
		$questions_array = array(); // 我关注的话题的问题集合
		$cache_key = ZCACHE::format_key('topics_get_all_best_question_by_topic_' . $_GET['topic_id'] . $limit);
		$action_list = ZCACHE::get($cache_key);
		
		if ($action_list === false)
		{
			if ($question_list = $this->model('topic')->get_all_best_question_by_topic($_GET['topic_id'], $limit))
			{
				foreach($question_list as $key=>$val)				
				{
					
					//是否关注
					if ($this->model('question')->has_focus_question($val['question_id'], $this->user_id))
					{
						$question_list[$key]['has_focus'] = true;
					}
					else
					{
						$question_info[$key]['has_focus'] = false;
					}
					
					
					$answer_list = $this->model('answer')->get_answer_info_by_id($val['best_answer']);
					$answer_list['attachs'] = $this->model('publish')->get_attach('answer', $val['best_answer'], 'min'); //获取附件
					
					if (! empty($answer_list))
					{
						$question_list[$key]['answer_info'] = $answer_list;
						$question_list[$key]['answer_info']['user_info']=$this->model('account')->get_users($answer_list['uid'],true);
						$question_list[$key]['answer_info']['agree_users']=$this->model("answer")->get_vote_user_by_answer_id($answer_list['answer_id']);
						$answer_vote = $this->model("answer")->get_answer_vote_status($answer_list['answer_id'], $this->user_id);
						$question_list[$key]['answer_info']['agree_status'] = intval($answer_vote['vote_value']);
					}
					$question_list[$key]['user_info']=$this->model('account')->get_users($val['published_uid'],true);
					
				}
			}

			$action_list=$question_list;

			ZCACHE::set($cache_key, $action_list, null, get_setting('cache_level_high'));
		}
	
		TPL::assign('action_list', $action_list);
		
		TPL::output('topic/ajax/all_best_question');		
		
	}

	public function topic_info_action()
	{
		$topic_id = $_GET['topic_id'];
		
		$topic_info = $this->model('topic')->get_topic($topic_id);
		$data['type'] = "topic";
		$data['topic_id'] = $topic_info['topic_id'];
		$data['topic_title'] = H::sensitive_words($topic_info['topic_title']);
		$data['topic_description'] = strip_tags(cjk_substr($topic_info['topic_description'], 0, 80, 'UTF-8', '...'));
		$data['focus_count'] = $topic_info['focus_count'];
		
		if ($this->user_id)
		{
			$data['focus'] = $this->model('topic')->has_focus_topic($this->user_id, $topic_id) ? true : false;
		}
		
		$data['discuss_count'] = $topic_info['discuss_count'];
		
		if (empty($topic_info['topic_pic']))
		{
			$data['topic_pic'] = G_STATIC_URL . '/common/topic-mid-img.jpg';
		}
		else
		{
			$data['topic_pic'] = get_setting('upload_url') . '/topic/' . $this->model('topic')->get_pic_url($topic_info['topic_id'], "mid", $topic_info['topic_pic']);
		}
		
		H::ajax_json_output($data);
	}

	public function modfiy_topic_title_action()
	{
		if (!($this->user_info['permission']['is_administortar'] OR $this->user_info['permission']['is_moderator']))
		{
			if (!$this->user_info['permission']['edit_topic'])
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', '你没有权限进行操作'));
			}
			else if ($this->model('topic')->has_lock_topic(intval($_GET['topic_id'])))
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', '锁定话题不能编辑'));
			}
		}
		
		$topic_id = intval($_GET['topic_id']);
		$topic_title = $_POST['topic_title'];
		
		$topic_info = $this->model('topic')->get_topic($topic_id);
		
		if ($topic_title == $topic_info['topic_title'])
		{
			H::ajax_json_output(AWS_APP::RSM(array(
				'url' => get_js_url('/topic/detail/' . $topic_id)
			), 1, '话题编辑成功'));
		}
		
		if ((get_setting('topic_title_limit') > 0) && (cjk_strlen($topic_title) > get_setting('topic_title_limit')))
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '话题标题字数不得超过' . get_setting('topic_title_limit') . '个'));
		}
		
		$topic_has_exist = $this->model('topic')->has_topic($topic_title);
		
		if ($topic_has_exist)
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '话题已经存在'));
		}
		
		if ($this->model('topic')->update_topic($topic_id, $topic_title))
		{
			H::ajax_json_output(AWS_APP::RSM(array(
				'url' => get_js_url('/topic/detail/' . $topic_id)
			), 1, '话题编辑成功'));
		}
		else
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '话题编辑失败, 请联系管理员'));
		}
	}
	
	public function save_related_topic_action()
	{
		if (!($this->user_info['permission']['is_administortar'] OR $this->user_info['permission']['is_moderator']))
		{
			if (!$this->user_info['permission']['edit_topic'])
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', '你没有权限进行操作'));
			}
			else if ($this->model('topic')->has_lock_topic($_GET['topic_id']))
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', '锁定话题不能编辑'));
			}
		}
		
		if (!$this->model('topic')->get_topic($_GET['topic_id']))
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '话题不存在'));
		}
		
		$topic_title = trim($_POST['topic_title']);
		
		if (!$topic_title)
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '请输入话题标题'));
		}
		
		if (preg_match('/\//is', $topic_title))
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '话题不能包含"/"'));
		}
		
		if ((get_setting('topic_title_limit') > 0) && (cjk_strlen($topic_title) > get_setting('topic_title_limit')))
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '话题标题字数不得超过' . get_setting('topic_title_limit') . '个'));
		}
		
		$related_id = $this->model('topic')->save_topic(0, $topic_title, $this->user_id, 0, '', '', 0, 2);
		
		if (!$this->model('topic')->save_related_topic($_GET['topic_id'], $related_id))
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '已经存在相同推荐话题'));
		}
		
		ACTION_LOG::save_action($this->user_id, $_GET['topic_id'], ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::ADD_RELATED_TOPIC, '', $related_id);
		
		H::ajax_json_output(AWS_APP::RSM(array(
			'related_id' => $related_id
		), 1, null));
	}
	
	public function remove_related_topic_action()
	{
		if (!($this->user_info['permission']['is_administortar'] OR $this->user_info['permission']['is_moderator']))
		{
			if (!$this->user_info['permission']['edit_topic'])
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', '你没有权限进行操作'));
			}
			else if ($this->model('topic')->has_lock_topic($_GET['topic_id']))
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', '锁定话题不能编辑'));
			}
		}
		
		$this->model('topic')->remove_related_topic($_GET['topic_id'], $_GET['related_id']);
		
		ACTION_LOG::save_action($this->user_id, $_GET['topic_id'], ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::DELETE_RELATED_TOPIC, '', $_GET['related_id']);
		
		H::ajax_json_output(AWS_APP::RSM(null, 1, null));
	}

	public function modify_topic_desc_action()
	{
		if (!$topic_info = $this->model('topic')->get_topic($_GET['topic_id']))
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '没有找到相关话题'));
		}
		
		if (!($this->user_info['permission']['is_administortar'] OR $this->user_info['permission']['is_moderator']))
		{
			if (!$this->user_info['permission']['edit_topic'])
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', '你没有权限进行操作'));
			}
			else if ($this->model('topic')->has_lock_topic($_GET['topic_id']))
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', '锁定话题不能编辑'));
			}
		}
		
		$topic_description = htmlspecialchars($_POST['topic_description']);
		
		if (empty($topic_description))
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '话题描述为空'));
		}
		
		$this->model('topic')->update_topic($_GET['topic_id'], '', $topic_description, '', '');
		
		ZCACHE::cleanGroup(ZCACHE::format_key('topic_info_' . $_GET['topic_id']));
			
		H::ajax_json_output(AWS_APP::RSM(null, 1, FORMAT::parse_links($topic_description)));
	}

	public function upload_topic_pic_action()
	{
		if (!($this->user_info['permission']['is_administortar'] OR $this->user_info['permission']['is_moderator']))
		{
			if (!$this->user_info['permission']['edit_topic'])
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', '你没有权限进行操作'));
			}
			else if ($this->model('topic')->has_lock_topic(intval($_GET['topic_id'])))
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', '锁定话题不能编辑'));
			}
		}
		
		define('IROOT_PATH', get_setting('upload_dir') . '/topic/');
		define('ALLOW_FILE_FIXS', '*');
		
		if (filesize($_FILES['topic_pic']['tmp_name']) > (get_setting('upload_avatar_size_limit') * 1024))
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', "话题缩略图文件尺寸过大, 最大允许尺寸为 " . get_setting('upload_avatar_size_limit') .  " KB"));
		}
		
		$date = date('Ymd');
		$topic_id = intval($_GET['topic_id']);
		
		if ($topic_id == 0)
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '话题 ID 错误'));
		}
		
		$topic_info = $this->model('topic')->get_topic($topic_id);
		
		if ($_FILES['topic_pic']['name'])
		{
			$this->model('image')->data_dir = "";
			$this->model('image')->images_dir = "";
			$random_filename = $this->model('image')->random_filename(2);
			$file_name = $this->model('image')->upload_image($_FILES['topic_pic'], $date, $random_filename);
			
			//生成缩图
			if (! $file_name)
			{
				H::ajax_json_output(AWS_APP::RSM(null, '-1', "图片格式错误"));
			}
			
			$file_name = IROOT_PATH . $file_name;
			$ext = $this->model('image')->get_filetype($file_name);
			
			foreach (AWS_APP::config()->get('image')->topic_thumbnail as $key => $val)
			{
				$thumb_file[$key] = $this->model('image')->make_thumb($file_name, $val['w'], $val['h'], IROOT_PATH . $date . "/", $random_filename . "_" . $val['w'] . "_" . $val['h'] . $ext, true);
			
			}
		}
		else
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '没选择图片'));
		}
		
		if ($thumb_file['mid'] === false)
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '图片上传错误, 请联系管理员'));
		}
		else
		{
			
			$topic_pic = $date . '/' . $thumb_file['min'];
			
			$this->model('topic')->modify_pic_topic_by_id($topic_id, $topic_pic);
			
			H::ajax_json_output(AWS_APP::RSM(array(
				'preview' => get_setting('upload_url') . '/topic/' . $date . '/' . $thumb_file['max']
			), '1', ''));
		}
	}

	/**
	 * 
	 * 关注话题
	 * 
	 * @return boolean true|false
	 */
	public function focus_topic_action()
	{
		$topic_id = intval($_GET['topic_id']);
		
		if ($topic_id == 0)
		{
			return false;
		}
		
		H::ajax_json_output(AWS_APP::RSM(array(
			'type' => $this->model('topic')->add_focus_topic($this->user_id, $topic_id)
		), '1', '关注话题成功'));
	}
		
	/**
	 * 
	 * 保存话题经验
	 */
	public function save_topic_experience_action()
	{
		$topic_id = intval($_GET['topic_id']);
		$experience_content = trim($_POST['experience_content']);
		
		if (!$topic_id OR !$experience_content)
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', "话请输入话题经验内容"));
		}
		
		if ($this->model('topic')->save_topic_experience($topic_id, $this->user_id, $experience_content))
		{
			H::ajax_json_output(AWS_APP::RSM(null, 1, nl2br($experience_content)));
		}
		else
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '话题经验修改失败, 请联系管理员'));
		}
	}
	
	/**
	 * 锁定/解锁话题
	 */
	public function lock_topic()
	{
		if (!$_GET['topic_id'])
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '没有找到相关话题'));
		}
		
		if (!$this->model('topic')->has_lock_topic($_GET['topic_id']))
		{
			$topic_lock = 1;
		}
		else
		{
			$topic_lock = 0;
		}
		
		if ($this->model('topic')->lock_topic_by_id($_GET['topic_id'], $topic_lock))
		{
			H::ajax_json_output(AWS_APP::RSM(null, '1'));
		}
		else
		{
			H::ajax_json_output(AWS_APP::RSM(null, '-1', '锁定/解锁话题失败。'));
		}
	}
	
	public function topic_share_txt_action()
	{
		$topic_id = intval($_GET['topic_id']);
		
		$topic_info = $this->model('topic')->get_topic($topic_id);
		
		//$topic_info['question_content'] = cjk_substr($q_info['question_content'], 0, 100, 'UTF-8', '...');
		
		$url = get_js_url("/topic/detail/" . $topic_id . "?fromuid-" . $this->user_id);
		
		$email_message = (array)AWS_APP::config()->get('email_message');
		
		foreach ($email_message[email_class::TYPE_TOPIC_SHARE] as $key => $val)
		{
			$$key = str_replace('[#user_name#]', $this->user_info['user_name'], $val);
			$$key = str_replace('[#site_name#]', get_setting('site_name'), $$key);
			$$key = str_replace('[#topic_title#]', $topic_info['topic_title'], $$key);
		}
		
		$data = array(
				'weibo' => "#" . get_setting('site_name') . "# " . $topic_info['topic_title'] . " " . $url . " (分享自@" . get_setting('site_name') . ")",
				'mail' => $message,
				'message' => "我看到一个不错的话题，想和你分享：“" . $topic_info['topic_title'] . "” " . $url,
				'url' => $url,
		);
		
		H::ajax_json_output(AWS_APP::RSM(array(
			'share_txt' => $data
		), 1));
	}
}